<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.admin"
          placeholder="用户类型"
          class="handle-select mr10"
        >
          <el-option key="2" label="全部" value=""></el-option>
          <el-option key="0" label="管理员" value="1"></el-option>
          <el-option key="1" label="普通用户" value="0"></el-option>
        </el-select>
        <el-input
          v-model="query.username"
          placeholder="用户名"
          class="handle-input mr10"
        ></el-input>
        <el-button
          admin="primary"
          icon="el-icon-search"
          @click="handleSearch"
          type="primary"
        >
          搜索
        </el-button>
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="uId"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="tel"
          label="用户电话"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column prop="sex" label="用户性别" width="80" align="center">
          <template #default="scope">
            <el-tag>
              {{ scope.row.sex == "1" ? "男" : "女" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="age"
          label="年龄"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户头像"
          width="260"
          align="center"
          prop="uImg"
        >
          <template #default="scope">
            <img :src="`${IMG_URL}${scope.row.uImg}`" width="80" height="80" />
          </template>
        </el-table-column>
        <el-table-column
          label="用户类型"
          width="100"
          align="center"
          prop="admin"
        >
          <template #default="scope">
            <el-tag
              :type="
                scope.row.admin == '1'
                  ? 'warning'
                  : scope.row.admin == '0'
                  ? ''
                  : ''
              "
            >
              {{
                scope.row.admin == "1"
                  ? "管理员"
                  : scope.row.admin == "0"
                  ? "普通用户"
                  : "未知"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" width="180" align="center">
          <template #default="scope">
            {{ moment(scope.row.createdAt).format("YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="createdAt" label="注册时间"></el-table-column> -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定要删除此用户"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="centerDialogVisible"
      title="用户编辑"
      width="40%"
      :before-close="cancel"
    >
      <el-scrollbar height="400px">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input
              v-model="ruleForm.password"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="电话号码" prop="tel">
            <el-input v-model="ruleForm.tel" />
          </el-form-item>
          <el-form-item label="用户性别" prop="sex">
            <el-radio-group v-model="ruleForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="ruleForm.age" />
          </el-form-item>
          <el-form-item label="用户头像">
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-remove="handledel"
              :on-change="changeUploadImg"
              ref="upload"
              :file-list="fileList"
              :multiple="true"
              name="file"
              v-model="fileList"
              :limit="1"
            >
              <el-icon>
                <Plus />
              </el-icon>
              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handledel(file)"
                    >
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传一张图片,且单张图片大小不能超过4MB
                </div>
              </template>
            </el-upload>
            <!--  放大的图片  -->
            <el-dialog v-model="dialogVisible" top="7vh">
              <img
                w-full
                :src="dialogImageUrl"
                alt="Preview Image"
                style="width: 100%; height: auto"
              />
            </el-dialog>
          </el-form-item>
          <el-form-item label="用户类型" prop="admin">
            <el-radio-group v-model="ruleForm.admin">
              <el-radio :label="1">管理员</el-radio>
              <el-radio :label="0">普通用户</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="用户状态" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="0">停用</el-radio>
              <el-radio :label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >更新</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
          <el-button @click="cancel(ticketFormRef)">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification } from "element-plus";
import moment from "moment";
import { IMG_URL } from "@/utils/imgStatic";
import { Delete, Plus, ZoomIn } from "@element-plus/icons-vue";

const tableData = ref([]);
const totalCount = ref(0);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);

// 移除图片
const handledel = (file) => {
  fileList.value = [];
};
//展示大图
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//限制大小
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeUploadImg = (file) => {
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  if (!isJPG && !isPNG) {
    ElNotification.error("上传图片只能是 JPG 或者 PNG 格式!");
    // 取消时在文件列表中删除该文件
    upload.value.handleRemove(file);
    return isJPG || isPNG;
  } else if (file.size / 1024 / 1024 > 4) {
    ElNotification.error("单张图片大小不能超过4MB!");
    return false;
  } else {
    fileList.value.push(file);
  }
};

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);
//取消表单
const cancel = (formEl) => {
  centerDialogVisible.value = false;
  fileList.value = [];
};
//重置表单
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("file", value.raw);
    });
    formData.append("uId", ruleForm.uId);
    formData.append("username", ruleForm.username);
    formData.append("password", ruleForm.password);
    formData.append("tel", ruleForm.tel);
    formData.append("sex", ruleForm.sex);
    formData.append("age", ruleForm.age);
    formData.append("uImg", ruleForm.uImg);
    formData.append("admin", ruleForm.admin);
    if (valid) {
      // console.log("提交更新", fields);
      request
        .patch("/user/updateUser", formData, {
          headers: {
            "Content-Type":
              "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            ElNotification({
              title: "更新成功",
              message: "成功更新用户信息",
            });
            //关闭表单
            centerDialogVisible.value = false;
            fileList.value = [];
            //重新查询数据
            getData();
          } else {
            ElNotification({
              title: "更新失败",
              message: "请联系管理员检查失败原因",
            });
          }
        })
        .catch((e) => {
          ElNotification({
            title: "更新失败",
            message: "请联系管理员检查失败原因",
          });
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
      });
    }
  });
};
const ruleForm = reactive({
  uId: "",
  username: "",
  password: "",
  tel: "",
  sex: "",
  age: "",
  uImg: "",
  admin: "",
});
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 1,
      max: 7,
      message: "长度大于1小于7",
      trigger: "blur",
    },
  ],
  tel: [
    {
      required: true,
      message: "请输入电话号码",
      trigger: "blur",
    },
    {
      min: 11,
      max: 11,
      message: "请输入11位电话号码",
      trigger: "blur",
    },
  ],
  sex: [
    {
      required: true,
      message: "请输入性别",
      trigger: "change",
    },
  ],
  age: [
    {
      required: true,
      message: "请输入年龄",
      trigger: "change",
    },
  ],
  admin: [
    {
      required: true,
      message: "请选择用户类型",
      trigger: "change",
    },
  ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);
const query = reactive({
  admin: "",
  username: "",
  currentPage: 1,
  pageSize: 3,
});

// 获取表格数据
const getData = () => {
  request
    .request({
      url: "/user/getAllUsersByPage",
      params: {
        username: query.username,
        admin: query.admin,
        currentPage: query.currentPage,
        pageSize: query.pageSize,
      },
      method: "get",
    })
    .then((res) => {
      //获取当前页的数据
      tableData.value = res.data.data.rows;
      //获取总记录数
      totalCount.value = res.data.data.count;
    })
    .catch((e) => {
      console.log(e);
    });
};
getData();
// 查询操作
const handleSearch = () => {
  getData();
};
// 分页导航
const handleCurrentChange = (val) => {
  query.currentPage = val;
  getData();
  // console.log(val);
};

// 删除操作
const handleDelete = (index, row) => {
  request
    .delete("/user/deleteUser", {
      params: {
        uId: row.uId,
      },
    })
    .then((res) => {
      if (res.data.msg == "success") {
        getData();
        ElNotification({
          title: "删除成功",
          message: "成功删除用户信息",
        });
      } else {
        ElNotification({
          title: "删除失败",
          message: "请联系管理员检查失败原因",
        });
      }
    })
    .catch((e) => {
      ElNotification({
        title: "删除失败",
        message: "请联系管理员检查失败原因",
      });
    });
};
const handleEdit = (index, row) => {
  centerDialogVisible.value = true;
  ruleForm.uId = row.uId;
  ruleForm.username = row.username;
  ruleForm.password = row.password;
  ruleForm.sex = parseInt(row.sex);
  ruleForm.age = row.age;
  ruleForm.tel = row.tel;
  ruleForm.uImg = row.uImg;
  ruleForm.admin = row.admin;
  fileList.value.push({
    url: `${IMG_URL}${row.uImg}`,
  });
};
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
